import { authorization } from './authorization.js'
import Result from '../datas/result.js'
const baseUrl = "http://localhost:8080"

const http = {
    get(url, header = {}) {
        return new Promise((resolve, reject) => {
            uni.request({
                url: baseUrl + url,
                method: 'GET',
                header: {
                    'Content-Type': 'application/json',
                    'Authorization': authorization.getToken(),
                    ...header
                },
                success: (res) => {
                    resolve(res.data)
                },
                fail: (err) => reject(err)
            })
        })
    },
    post(url, data, header = {}) {
        return new Promise((resolve, reject) => {
            uni.request({
                url: baseUrl + url,
                method: 'POST',
                data: data,
                header: {
                    'Content-Type': 'application/json',
                    'Authorization': authorization.getToken(),
                    ...header
                },
                success: (res) => {
                    resolve(res.data)
                },
                fail: (err) => reject(err)
            })
        })
    }
};

const fileHttp = {
    upload(url, filePath, header = {}) {
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: baseUrl + url,
                name: 'file',
                filePath: filePath,
                header: {
                    // 'Content-Type': 'multipart/form-data',
                    'Authorization': authorization.getToken(),
                    ...header
                },
                success: (res) => {
                    resolve(Result.fromJson(res.data))
                },
                fail: (err) => reject(err)
            })
        })
    },
    download(url, header = {}) {
        return new Promise((resolve, reject) => {
            uni.downloadFile({
                url: baseUrl + url,
                header: {
                    'Authorization': authorization.getToken(),
                    ...header
                },
                success: (res) => {
                    resolve(Result.fromJson(res.data))
                },
                fail: (err) => reject(err)
            })
        })
    }
}

export { http, fileHttp, baseUrl }